package com.itboye.mengwu.app.ui.mymeng;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
import java.util.Observable;
import java.util.Observer;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.itboye.core.alert.ByAlert;
import com.itboye.core.object.BaseActivity;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.CameraPopupWindow;
import com.itboye.core.utils.ImageCompress;
import com.itboye.core.utils.SPUtils;
import com.itboye.core.utils.SexPopupWindow;
import com.itboye.core.utils.UploadImage;
import com.itboye.core.utils.UploadImage.OnUploadlistener;
import com.itboye.core.utils.XImageLoader;
import com.itboye.inageview.RoundImageView;
import com.itboye.mengwu.R;
import com.itboye.mengwu.app.MainApplication;
import com.itboye.mengwu.app.logincontroller.LoginController;
import com.itboye.mengwu.app.ui.main.MainPresenter;
import com.itboye.mengwu.app.ui.mymeng.ActivityChooseBaby.MyAdapter;
import com.itboye.mengwu.cliptools.ClipActivity;
import com.itboye.mengwu.data.model.AddressQueryModel;
import com.itboye.mengwu.data.model.BabyBean;
import com.itboye.mengwu.data.model.PersonDataBean;
import com.itboye.mengwu.data.presenter.AddressQueryPresenter;
import com.itboye.mengwu.data.presenter.BabyPresenter;
import com.itboye.mengwu.data.repository.UserRepository;

public class ActivityGeRenData extends BaseActivity implements Observer,
		OnUploadlistener {
	MainPresenter mainPresenter;
	TextView txt_title;
	ImageView back;
	ImageView img_other;
	TextView txt_save;
	TextView touxiang;
	EditText userName_txt;
	EditText nickName_txt;
	// TextView babybirth_txt;
	TextView sex_txt, baobaoxiaoming_txt;
	EditText qianming_txt;
	RoundImageView usericon_im;
	MyAdapter adapter;
	RelativeLayout user_image_layout, userName_layout, nick_name_layout,
			change_sex_layout, qianming_layout, baby_birth_layout,
			babyxiaoming_layout;
	CameraPopupWindow cameraPopupWindow;
	protected SexPopupWindow mSexPopupWindow;
	// 使用相机拍照
	private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 110;
	// 获取日期格式器对象
	DateFormat fmtDate = new java.text.SimpleDateFormat("yyyy年MM月dd日");

	private String picture_name;
	private String fileName;
	private String localSelectPath;
	private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
	private static final int PHOTO_REQUEST_CUT = 3;// 结果

	private Calendar dateAndTime;
	private String sex;
	ArrayList<BabyBean> babyarrayList = new ArrayList<BabyBean>();
	BabyPresenter babyPresenter;
	RelativeLayout address_layout;
	AddressQueryPresenter addressQueryPresenter;
	ArrayList<AddressQueryModel> arrayListAddress;
	ArrayList<AddressQueryModel> arrayListAddressCopy;
	TextView address_txt;

	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.activity_gerendata;
	}

	@Override
	public void onMyCreate() {
		showProgressDialog("数据加载中，请稍后...", true);
		addressQueryPresenter = new AddressQueryPresenter(this);
		addressQueryPresenter.queryAddress(SPUtils.get(this, null,
				SpPublicParams.UID, "") + "");
		arrayListAddress = new ArrayList<AddressQueryModel>();
		arrayListAddressCopy = new ArrayList<AddressQueryModel>();
		babyPresenter = new BabyPresenter(this);
		babyPresenter.BabyAll(SPUtils.get(this, null, SpPublicParams.UID, "")
				+ "");

		// 获取一个日历对象
		dateAndTime = Calendar.getInstance(Locale.CHINA);
		// baby_birth_layout.setOnClickListener(onclicklister);

		String uid = (String) SPUtils.get(this, null, SpPublicParams.UID, "");
		String userName = (String) SPUtils.get(this, null,
				SpPublicParams.USER_NAME, "");
		userName_txt.setText(userName);
		String nickName = (String) SPUtils.get(this, null,
				SpPublicParams.NICK_NAME, "");
		nickName_txt.setText(nickName);
		qianming_txt.setText((String) SPUtils.get(this, null,
				SpPublicParams.SIGNATURE, ""));
		address_layout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				LoginController.onAddress(ActivityGeRenData.this, null);
			}
		});

		try {
			sex = (String) SPUtils.get(this, null, SpPublicParams.SEX, "");

		} catch (Exception e) {
			// TODO: handle exception
			sex = SPUtils.get(this, null, SpPublicParams.SEX, 1) + "";
		}
		try {
			if (Integer.parseInt(sex) == 1) {
				sex_txt.setText("宝爸");
			} else if (Integer.parseInt(sex) == 0) {
				sex_txt.setText("宝妈");
			} else {
				sex_txt.setText("保密");
			}
			if ("".equals((String) SPUtils.get(this, null,
					SpPublicParams.USERHEAD, "")) && Integer.parseInt(sex) == 1) {
				usericon_im.setImageResource(R.drawable.male);

			} else if ("".equals((String) SPUtils.get(this, null,
					SpPublicParams.USERHEAD, "")) && Integer.parseInt(sex) == 0) {
				usericon_im.setImageResource(R.drawable.female);
			} else {
				XImageLoader.load((String) SPUtils.get(this, null,
						SpPublicParams.USERHEAD, ""), usericon_im);
			}
		} catch (Exception e) {
			// TODO: handle exception
			sex_txt.setText("保密");
			XImageLoader.load((String) SPUtils.get(this, null,
					SpPublicParams.USERHEAD, ""), usericon_im);
		}

		String signature = (String) SPUtils.get(this, null,
				SpPublicParams.SIGNATURE, "");
		if (signature == null || signature == "") {
			qianming_txt.setText("还没有签名哦！");
		} else {
			qianming_txt.setText(signature);
		}
		txt_title.setText("个人资料");
		img_other.setVisibility(View.GONE);
		txt_save.setVisibility(View.VISIBLE);
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		user_image_layout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				cameraPopupWindow = new CameraPopupWindow(
						ActivityGeRenData.this, onclicklister);
				cameraPopupWindow.showAtLocation(v, Gravity.BOTTOM
						| Gravity.CENTER_HORIZONTAL, 0, 0);
			}
		});

		change_sex_layout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
						.hideSoftInputFromWindow(ActivityGeRenData.this
								.getCurrentFocus().getWindowToken(),
								InputMethodManager.HIDE_NOT_ALWAYS);
				mSexPopupWindow = new SexPopupWindow(ActivityGeRenData.this,
						onclicklister);
				mSexPopupWindow.showAtLocation(v, Gravity.BOTTOM
						| Gravity.CENTER_HORIZONTAL, 0, 0);
			}
		});
		qianming_layout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

			}
		});
		babyxiaoming_layout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(ActivityGeRenData.this,
						ActivityChooseBaby.class);
				startActivity(intent);
			}
		});

		txt_save.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// showProgressDialog("正在保存，请稍后", true);
				mainPresenter = new MainPresenter(ActivityGeRenData.this);
				PersonDataBean bean = new PersonDataBean();
				bean.setType(2);
				bean.setUid((String) SPUtils.get(ActivityGeRenData.this, null,
						SpPublicParams.UID, ""));
				bean.setUsername(userName_txt.getText().toString().trim());
				if (nickName_txt.getText().length() > 16) {
					ByAlert.alert("名字不能超过16个字哦");
					return;
				} else {
					bean.setNickname(nickName_txt.getText().toString().trim());
				}
				// bean.setHead("");
				if (sex_txt.getText().toString().equals("宝爸")) {
					bean.setSex(1 + "");
				} else if (sex_txt.getText().toString().equals("宝妈")) {
					bean.setSex(0 + "");
				} else {
					bean.setSex("保密");
				}
				bean.setSign(qianming_txt.getText() + "");
				mainPresenter.updateUserInfoByUid(bean);
				// finish();
				try {
					closeProgressDialog();
				} catch (Exception e) {
					// TODO: handle exception
				}
			}

		});
	}

	private void SaveUserName(String username) {
		// TODO Auto-generated method stub
		nickName_txt.setText(username);
	}

	private OnClickListener onclicklister = new OnClickListener() {
		@Override
		public void onClick(View view) {
			// TODO Auto-generated method stub
			switch (view.getId()) {
			case R.id.open_camera:
				/**
				 * 打开照相机
				 */
				String state = Environment.getExternalStorageState();
				if (state.equals(Environment.MEDIA_MOUNTED)) {
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					startActivityForResult(intent,
							CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
				} else {
					Toast.makeText(ActivityGeRenData.this, "请确认已经插入SD卡", 0)
							.show();
				}
				break;
			case R.id.pick_image:
				// new PhotoSelectFragment(new PhotoSelect(),
				// 6 - imgContainer.getChildCount() + 1).show(
				// getSupportFragmentManager(), null);
				// 激活系统图库，选择一张图片
				Intent intent = new Intent(Intent.ACTION_PICK);
				intent.setType("image/*");
				// 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY
				startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
				break;
			case R.id.img:
				break;
			case R.id.boy_tv:
				// 性别男
				putchangesex("宝爸");
				mSexPopupWindow.dismiss();
				if ("".equals((String) SPUtils.get(ActivityGeRenData.this,
						null, SpPublicParams.USERHEAD, ""))) {
					usericon_im.setImageResource(R.drawable.male);
				}
				break;
			case R.id.girl_tv:
				// 性别女

				putchangesex("宝妈");
				mSexPopupWindow.dismiss();
				if ("".equals((String) SPUtils.get(ActivityGeRenData.this,
						null, SpPublicParams.USERHEAD, ""))) {
					usericon_im.setImageResource(R.drawable.female);

				}
				break;
			case R.id.secrecy_tv:
				// 性别保密
				putchangesex("保密");
				mSexPopupWindow.dismiss();
				break;
			case R.id.baby_birth_layout:

				// 当点击DatePickerDialog控件的设置按钮时，调用该方法
				DatePickerDialog.OnDateSetListener d = new DatePickerDialog.OnDateSetListener() {
					@Override
					public void onDateSet(DatePicker view, int year,
							int monthOfYear, int dayOfMonth) {
						// 修改日历控件的年，月，日
						// 这里的year,monthOfYear,dayOfMonth的值与DatePickerDialog控件设置的最新值一致
						dateAndTime.set(Calendar.YEAR, year);
						dateAndTime.set(Calendar.MONTH, monthOfYear);
						dateAndTime.set(Calendar.DAY_OF_MONTH, dayOfMonth);
						// //将页面TextView的显示更新为最新时间
						upDateDate();

					}
				};
				DatePickerDialog dateDlg = new DatePickerDialog(
						ActivityGeRenData.this, d,
						dateAndTime.get(Calendar.YEAR),
						dateAndTime.get(Calendar.MONTH),
						dateAndTime.get(Calendar.DAY_OF_MONTH));

				dateDlg.show();
				break;
			default:
				break;
			}
		}

	};

	private void upDateDate() {
		// babybirth_txt.setText(fmtDate.format(dateAndTime.getTime()));
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE
				&& resultCode == RESULT_OK) {

			if (data == null) {
				cameraPopupWindow.dismiss();
				return;
			}
			String sdStatus = Environment.getExternalStorageState();
			if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
				return;
			}

			picture_name = android.text.format.DateFormat.format(
					"yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA))
					+ ".jpg";
			Bundle bundle = data.getExtras();
			Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
			File file = new File("/sdcard/Image/");
			file.mkdirs();// 创建文件夹
			fileName = "/sdcard/Image/" + picture_name;

			FileOutputStream b = null;
			try {
				b = new FileOutputStream(fileName);
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} finally {
				try {
					b.flush();
					b.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			UploadImage.getInstance().execute(fileName, this);
			cameraPopupWindow.dismiss();
		} else if (requestCode == PHOTO_REQUEST_GALLERY) {
			// 从相册返回的数据
			if (data != null) {
				/**
				 * 当选择的图片不为空的话，在获取到图片的途径
				 */
				Uri selectedImage = data.getData();
				localSelectPath = null;
				// Cursor cursor = this.getContentResolver().queryYouHuiQuan(
				// data.getData(), null, null, null, null);
				// cursor.moveToFirst();
				// int columnIndex = cursor.getColumnIndex("_data");
				// localSelectPath = cursor.getString(columnIndex);
				localSelectPath = getRealPathFromURI(selectedImage);
				localSelectPath = ImageCompress.compress(localSelectPath);
				Intent intent2 = new Intent(ActivityGeRenData.this,
						ClipActivity.class);
				intent2.putExtra("path", localSelectPath);
				startActivityForResult(intent2, IMAGE_COMPLETE);
			}

		} else if (requestCode == IMAGE_COMPLETE) {

			if (data == null) {
				cameraPopupWindow.dismiss();
				return;
			}
			UploadImage.getInstance().execute(localSelectPath, this);
			cameraPopupWindow.dismiss();

		}
	};

	public static final int IMAGE_COMPLETE = 6; // 结果

	/**
	 * This method is used to get real path of file from from uri<br/>
	 * http://stackoverflow.com/questions/11591825/how-to-get-image-path-just-
	 * captured-from-camera
	 * 
	 * @param contentUri
	 * @return String
	 */
	public String getRealPathFromURI(Uri contentUri) {
		try {
			String[] proj = { MediaStore.Images.Media.DATA };
			@SuppressWarnings("deprecation")
			Cursor cursor = this.managedQuery(contentUri, proj, null, null,
					null);
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			return cursor.getString(column_index);
		} catch (Exception e) {
			return contentUri.getPath();
		}
	}

	private void putchangesex(String sex) {
		// TODO Auto-generated method stub
		sex_txt.setText(sex);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		babyPresenter.BabyAll(SPUtils.get(this, null, SpPublicParams.UID, "")
				+ "");
		addressQueryPresenter.queryAddress(SPUtils.get(this, null,
				SpPublicParams.UID, "") + "");

	}

	private void upbabyname(String data) {
		// TODO Auto-generated method stub
		baobaoxiaoming_txt.setText(data);
	};

	@SuppressWarnings("unchecked")
	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity resultEntity = handlerError(data);
		if (resultEntity != null) {
			if (resultEntity.getEventType() == MainPresenter.UpdateUserInfoSuccessEvent) {
				ByAlert.alert(resultEntity.getData() + "");
				SPUtils.put(MainApplication.context, null,
						SpPublicParams.USER_NAME, userName_txt.getText());
				SPUtils.put(MainApplication.context, null,
						SpPublicParams.NICK_NAME, nickName_txt.getText());
				if (sex_txt.getText().toString().equals("宝爸")) {
					SPUtils.put(MainApplication.context, null,
							SpPublicParams.SEX, "1");

				} else if (sex_txt.getText().toString().equals("宝妈")) {
					SPUtils.put(MainApplication.context, null,
							SpPublicParams.SEX, "0");
					if ("".equals((String) SPUtils.get(this, null,
							SpPublicParams.USERHEAD, ""))
							&& sex_txt.getText().toString().equals("宝妈")) {
						usericon_im.setImageResource(R.drawable.female);
					}
				} else {
					SPUtils.put(MainApplication.context, null,
							SpPublicParams.SEX, "2");
				}

				SPUtils.put(MainApplication.context, null,
						SpPublicParams.SIGNATURE, qianming_txt.getText());
				finish();
			} else if (resultEntity.getEventType() == MainPresenter.UpdateUserInfoFailureEvent) {
				// ByAlert.alert(resultEntity.getData() + "");
			} else if (resultEntity.getEventType() == BabyPresenter.BABYALL_success) {
				ArrayList<BabyBean> baby;
				baby = (ArrayList<BabyBean>) resultEntity.getData();
				for (int i = 0; i < baby.size(); i++) {
					if ("1".equals(baby.get(i).getIs_default())) {
						String babynameString = baby.get(i).getBaby_name();
						upbabyname(babynameString);
					}
					if ("0".equals(baby.get(i).getIs_default())) {
						String babynameString = baby.get(0).getBaby_name();
						upbabyname(babynameString);
					}
				}

			} else if (resultEntity.getEventType() == AddressQueryPresenter.AddressQuerySuccessEvent) {
				arrayListAddress.clear();
				arrayListAddressCopy.clear();
				arrayListAddress
						.addAll((ArrayList<AddressQueryModel>) resultEntity
								.getData());
				if (arrayListAddress.size() == 0) {
					address_txt.setText("还没有地址");
				} else {
					for (int i = 0; i < arrayListAddress.size(); i++) {
						if (arrayListAddress.get(i).getDefault() == 1) {
							arrayListAddressCopy
									.add(0, arrayListAddress.get(i));
							if (arrayListAddressCopy.size() == 0) {
								address_txt.setText(arrayListAddress.get(0)
										.getProvince()
										+ arrayListAddress.get(0).getCity()
										+ arrayListAddress.get(0).getArea()
										+ arrayListAddress.get(0)
												.getDetailinfo() + "");
							} else {
								address_txt.setText(arrayListAddress.get(i)
										.getProvince()
										+ arrayListAddress.get(i).getCity()
										+ arrayListAddress.get(i).getArea()
										+ arrayListAddress.get(i)
												.getDetailinfo());
							}

						} else {

							arrayListAddressCopy.add(arrayListAddress.get(i));
						}
					}
				}

			}
			try {
				closeProgressDialog();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	}

	@Override
	public void OnSuccess(String resultData) {

		Toast.makeText(getApplicationContext(), "上传成功", 0).show();
		// SPUtils.put(this, null, SpPublicParams.USERHEAD, localSelectPath);
		XImageLoader.load(
				(String) SPUtils.get(this, null, SpPublicParams.USERHEAD, ""),
				usericon_im);
	}

	@Override
	public void OnError(String resultData) {

	}
}
